#!/bin/bash
# Copyright (c) 2017 ~ 2025, the original author wangl.sir individual Inc,
# All rights reserved. Contact us <wanglsir@gmail.com, 983708408@qq.com>
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# cat /etc/etcd/etcd.conf | while read etcdVar; do
# if [[ -n "$(echo $etcdVar|sed 's/ //g')" && -z "$(echo $etcdVar|grep -E '^#|^export')" ]]; then
#   etcdVarName=$(echo $etcdVar|awk -F '=' '{print $1}'|sed 's/ //g')
#   etcdVarVal=$(echo $etcdVar|awk -F '=' '{print $2}'|sed 's/ //g')
#   eval "export $etcdVarName=\"$etcdVarVal\""
# fi
# done

. /etc/etcd/etcd.conf
export PATH=$PATH:/usr/lib/etcd-current

# This is a foolish parameter.
# Used to indicate whether this is a new cluster. There are two values, 'new' and 'existing'. 
# If it is set to 'existing', the member will try to interact with other members when starting.
# When creating a cluster for the first time, it should be set to 'new'. After trying, it is 
# normal for the last node to fill in 'existing', and other nodes cannot be set to 'existing'
# During cluster operation, when a member recovers after failure, it is set to 'existing', 
# and it is normal to try to set it to 'new'.
#
# see: https://etcd.io/docs/v3.5/op-guide/configuration/#--initial-cluster-state.
# see: https://github.com/etcd-io/etcd/blob/v3.5.0/server/etcdserver/server.go#L424
# see: https://my.oschina.net/u/160697/blog/4283750
#
# The naming rule: etcd1/etcd2/etcd3, the default set first 'etcd1' is leader.
#IS_LEADER="$([ "$ETCD_NAME" == "etcd1" ] && echo Y || echo N)"
#if [[ $IS_LEADER == 'Y' && -f "$ETCD_DATA_DIR/member/snap/db" ]]; then
if [[ -f "$ETCD_DATA_DIR/member/snap/db" ]]; then
  export ETCD_INITIAL_CLUSTER_STATE='new'
else
  export ETCD_INITIAL_CLUSTER_STATE='existing'
fi